package com.example.androidtest_update;

import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;

import cn.bvin.lib.app.WiseActivity;
import cn.bvin.lib.module.downloads.DownloadManager;
import cn.bvin.lib.module.downloads.DownloadManager.Request;
import cn.bvin.lib.module.downloads.Downloads;
import cn.bvin.lib.module.net.MapParam;
import cn.bvin.lib.module.net.convert.GsonDataConvertor;
import cn.bvin.lib.module.update.UpdateInfo;
import cn.bvin.lib.module.update.UpdateManager;
import cn.bvin.lib.module.update.UpdateManager.UpdateConfirmListener;
import cn.bvin.lib.module.update.model.UpdateModel;
import cn.bvin.library.debug.SimpleLogger;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends WiseActivity {

	String url = "http://lite.phone.bacic5i5j.com/PhoneOA/ReqWeb/System/System.ashx";
	
	private DownloadManager dm;
	private long currentDownloadId;//断点续传要依靠这个来恢复之前下载进度
	private ProgressDialog pd;
	
	DownloadObserver observer;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		parserIntent();
		initData();
		initViews(R.layout.activity_main);
		autoCheckUpdate();
	}

	@Override
	public void parserIntent() {
		super.parserIntent();
		
	}

	@Override
	public void initData() {
		super.initData();
		currentDownloadId = getPreferences(MODE_PRIVATE).getLong("currentDownloadId", -1);
		if (currentDownloadId>=0) {
			observer = new DownloadObserver(handler, currentDownloadId);
			getContentResolver().registerContentObserver(Downloads.CONTENT_URI, true, observer);
		}
		dm = new DownloadManager(getContentResolver(), getPackageName());
	}

	
	
	@Override
	public void initViews(int layoutResID) {
		super.initViews(layoutResID);
	}

	private void autoCheckUpdate() {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("Method", "UpdateApk");
		UpdateManager.with(this).checkVersion(url, params,new GsonDataConvertor<UpdateInfo>() {
			//转换器的作用主要是让监听器得到数据是准确的
			@Override
			public UpdateInfo convertFromGson(byte[] data, Class clazz) {
				String json = new String(data);
				Gson gson = new Gson();
				UpdateModel modal = gson.fromJson(json, clazz);
				UpdateInfo info = new UpdateInfo(modal.version,modal.note,modal.url,modal.lenth);
				return info;
			}

			@Override
			public Class jsonModel() {
				return UpdateModel.class;
			}
		}).listenUpdateConfirm(new UpdateConfirmListener() {
			
			@Override
			public void onUpdateConfirm(UpdateInfo info) {
				SimpleLogger.log_e("onUpdateConfirm", currentDownloadId<0);
				if (currentDownloadId<0) {
					startDownload(info);
				}else {
					resureDownload();
				}
				showDownloadDialog();
			}
		});
	}
	
	private void showDownloadDialog() {
		if (pd==null) {
			pd = new ProgressDialog(this);
			pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			pd.setTitle("更新中...");
			pd.setCancelable(false);
			pd.setButton(DialogInterface.BUTTON_POSITIVE, flag?"暂停":"恢复", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if (flag) {
						pauseDownload();
						flag = false;
					}else {
						resureDownload();
						flag = true;
					}
					
				}
			});
		}
		pd.show();
	}
	
	boolean flag = true;
	
	private void notifProgressDialog(int max, int value) {
		pd.setMax(max);
		pd.setProgress(value);
	}
	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			int total = msg.arg1;
			notifProgressDialog(total, msg.what);
		}
	};
	
	public class DownloadObserver extends ContentObserver{

		long id;
		Handler handler;
		
		public DownloadObserver(Handler handler, long id) {
			super(handler);
			this.id = id;
			this.handler = handler;
		}

		@Override
		public void onChange(boolean selfChange, Uri uri) {
			if (id<0) {
				return;
			}
			Cursor cursor = query(id);
			if (cursor!=null&&cursor.moveToFirst()) {
				Message msg = handler.obtainMessage();
				msg.what = cursor.getInt(cursor.getColumnIndex(Downloads.COLUMN_CURRENT_BYTES));
				msg.arg1 = cursor.getInt(cursor.getColumnIndex(Downloads.COLUMN_TOTAL_BYTES));
				SimpleLogger.log_e("总共："+msg.arg1, "当前："+msg.what);
				handler.sendMessage(msg); 
			}
			cursor.close();
		}
		private Cursor query(long id) {
			Uri uri = ContentUris.withAppendedId(Downloads.CONTENT_URI, id);
			return getContentResolver().query(uri, new String[]{Downloads.COLUMN_CURRENT_BYTES,
					Downloads.COLUMN_TOTAL_BYTES}, null, null, null);
		}
		
	}
	
	
	//开始下载，当currentDownloadId<0开始下载
	private void startDownload(UpdateInfo info) {
		Uri srcUri = Uri.parse(info.apkUrl);
		DownloadManager.Request request = new Request(srcUri);
		request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/");
		currentDownloadId = dm.enqueue(request);
		if (observer!=null) {
			observer = new DownloadObserver(handler, currentDownloadId);
			getContentResolver().registerContentObserver(Downloads.CONTENT_URI, true, observer);
		}
		//保存当前下载查询句柄
		getPreferences(MODE_PRIVATE).edit().putLong("currentDownloadId", currentDownloadId).commit();
	}
	
	//暂停下载
	public void pauseDownload() {
		dm.pauseDownload(currentDownloadId);
	}
	
	//恢复下载
	private void resureDownload() {
		dm.resumeDownload(currentDownloadId);
	}
	
	
	
}
